package util;

import java.lang.reflect.Array;

/**
 * This is a class of array utility functions.
 *
 * @author Neil Dickson
 */
public final class ArrayUtil {
	public static boolean containsExact(Object[] array,Object o) {
		for (Object obj : array) {
			if (obj==o) {
				return true;
			}
		}
		return false;
	}
	public static int indexOf(int[] array, int element) {
		for (int i=0;i<array.length;++i) {
			if (array[i]==element) {
				return i;
			}
		}
		return -1;
	}

	public static int indexOf(char[] array, char element) {
		for (int i=0;i<array.length;++i) {
			if (array[i]==element) {
				return i;
			}
		}
		return -1;
	}
	public static int indexOf(String[] array, String element) {
		for (int i=0;i<array.length;++i) {
			if (array[i].equals(element)) {
				return i;
			}
		}
		return -1;
	}

	public static byte[] subarray(byte[] array, int start, int end) {
		byte[] newArray = new byte[end-start];
		System.arraycopy(array,start,newArray,0,end-start);
		return newArray;
	}

	public static char[] subarray(char[] array, int start, int end) {
		char[] newArray = new char[end-start];
		System.arraycopy(array,start,newArray,0,end-start);
		return newArray;
	}

	public static int[] subarray(int[] array, int start, int end) {
		int[] newArray = new int[end-start];
		System.arraycopy(array,start,newArray,0,end-start);
		return newArray;
	}

	public static boolean[] subarray(boolean[] array, int start, int end) {
		boolean[] newArray = new boolean[end-start];
		System.arraycopy(array,start,newArray,0,end-start);
		return newArray;
	}

	public static Object[] subarray(Object[] array, int start, int end) {
		Object[] newArray = (Object[])Array.newInstance(array.getClass().getComponentType(),end-start);
		System.arraycopy(array,start,newArray,0,end-start);
		return newArray;
	}

	public static double[] rawBytesToDoubles(byte[] bytes) {
		double[] doubles = new double[bytes.length/8];
		int byteIndex = 0;
		for (int i=0;i<doubles.length;++i) {
			long bits = 0;
			for (int j=0;j<8;++j) {
				bits |= (bytes[byteIndex++]&0xFFL)<<(j*8);
			}
			doubles[i] = Double.longBitsToDouble(bits);
		}
		return doubles;
	}

	public static int indexOf(Object[] array, Object element) {
		for (int i=0;i<array.length;++i) {
			if (array[i]==element) {
				return i;
			}
		}
		return -1;
	}

	public static int[] allIndicesOf(Object[] array, Object element) {
		if (!containsExact(array,element)) {
			return null;
		}
		int count = 0;
		for (Object a : array) {
			if (a==element) {
				++count;
			}
		}
		int[] indices = new int[count];
		count = 0;
		for (int i=0;i<array.length;++i) {
			if (array[i]==element) {
				indices[count] = i;
				++count;
			}
		}
		return indices;
	}
}
